<template>
    <div id="classes">
        <el-breadcrumb class="common-bread">
            <el-breadcrumb-item>班级管理</el-breadcrumb-item>
        </el-breadcrumb>

        <div class="contentBox">
            <div>
                <label class="label">学校：</label>
                <el-autocomplete v-model="schoolName" :fetch-suggestions="querySearch" placeholder="请输入学校名称"
                    @select="handleSelect" clearable @clear="clearSch"></el-autocomplete>
                <label class="label">年级：</label>
                <el-select v-model="gradeId">
                    <el-option label='全部' value='0'></el-option>
                    <el-option :label='item.gradeName' :value='item.gradeId' :key='item.gradeId' v-for="item in grades">
                    </el-option>
                </el-select>
                <el-button type="primary" @click="getList(1)">搜索</el-button>
                <el-button type="primary" @click="newClass()" class="fr" icon="el-icon-circle-plus-outline">添加班级
                </el-button>
            </div>
            <div class="list">
                <el-table :data="list">
                    <el-table-column type="index" label="序号">
                    </el-table-column>
                    <el-table-column prop="schoolName" label="学校">
                    </el-table-column>
                    <el-table-column prop="name" label="班级">
                    </el-table-column>
                    <el-table-column prop="classNumber" label="班级编号">
                    </el-table-column>
                    <el-table-column prop="count" label="学生数量">
                    </el-table-column>
                    <el-table-column label="操作">
                        <template slot-scope="scope">
                            <i class="el-icon-document blueIcon" @click="toDet(scope.row)" title="查看详情"></i>
                            <i class="el-icon-edit blueIcon" @click="newClass(scope.row)" title="编辑"></i>
                            <i class="el-icon-delete redIcon" @click="deleteClass(scope.row)" title="删除"
                                v-if="!scope.row.count"></i>
                        </template>
                    </el-table-column>
                </el-table>
                <div class="pagination">
                    <el-pagination v-show="this.totalCount > 10" layout="total,prev, pager, next, jumper"
                        :page-size="10" :current-page="currentPage" :total="totalCount"
                        @current-change="handleCurrentChange">
                    </el-pagination>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
    import { mapState, mapActions } from "vuex";

    export default {
        data() {
            return {
                gradeId: "0",
                schoolType: [],
                schoolName: "",
                schoolId: "",
                schools: [],
                grades: this.$util.getGrades(),
                list: [],
                totalCount: 0,
                currentPage: 1
            }
        },
        computed: mapState({ user: state => state.user }),
        mounted() {
            this.$util.getSchools().then(schools => {
                let classSelect = this.$util.getStore("classSelect");
                let classInfo = JSON.parse(this.$util.getStore("classInfo"));
                if (classSelect == 1 && classInfo) {
                    this.currentPage = classInfo.pageNum * 1;
                    this.schoolName = classInfo.schoolName;
                    this.schoolId = classInfo.schoolId;
                    this.gradeId = classInfo.grade ? classInfo.grade * 1 : "0";
                    this.schoolType = classInfo.schoolType || ["小学", "初中", "高中"];
                    this.grades = this.$util.getGrades(this.schoolType);
                }
                this.getList(this.currentPage);
                this.$util.removeStore("classSelect");
                this.$util.removeStore("classInfo");

                schools.forEach(item => {
                    this.schools.push({
                        value: item.name,
                        schoolId: item.schoolId,
                        haveHigh: item.haveHigh,
                        haveMiddle: item.haveMiddle,
                        havePrimary: item.havePrimary
                    })
                });
            });
        },
        methods: {
            createFilter(queryString) {
                return (school) => {
                    return (school.value.toLowerCase().indexOf(queryString.toLowerCase()) >= 0);
                };
            },
            querySearch(queryString, cb) {
                let schools = this.schools;
                let results = queryString ? schools.filter(this.createFilter(queryString)) : schools;
                // 调用 callback 返回建议列表的数据
                cb(results);
                results = [];
            },
            handleSelect(item) {
                let schoolType = [];
                if (item.haveHigh) schoolType.push("高中");
                if (item.haveMiddle) schoolType.push("初中");
                if (item.havePrimary) schoolType.push("小学");
                this.schoolId = item.schoolId;
                this.schoolType = schoolType;
                this.grades = this.$util.getGrades(schoolType);
                this.gradeId = "0";
            },
            clearSch() {
                this.grades = this.$util.getGrades();
            },
            //获取班级列表
            getList(pageNum) {
                if (pageNum != this.currentPage) this.currentPage = pageNum;
                let params = {
                    grade: this.gradeId * 1,
                    pageSize: 10,
                    pageNum: pageNum * 1,
                    schoolType: this.schoolType,
                    schoolName: this.schoolName
                }
                if (this.gradeId == 0) delete params.grade;
                if (this.schoolId && this.schoolName) params.schoolId = this.schoolId;
                this.$util.setStore("classInfo", params);
                delete params.schoolName;
                delete params.schoolType;
                this.$axios.get("/adminapi/v1/tools/classes/list", {
                    params: params
                }).then(response => {
                    if (response.data.error == 10000) {
                        this.list = [];
                        this.totalCount = 0;
                        if (!response.data.data) return;

                        response.data.data.content.forEach(item => {
                            let gradeName = this.$util.gradeFormat(item.grade * 1);
                            let className = gradeName + item.number + "班";
                            item.name = item.name ? className + `（${item.name}）` : className;
                        })

                        this.list = response.data.data.content;
                        this.totalCount = response.data.data.total;
                    } else {
                        this.$util.errorMsg(response.data.message);
                    }
                })
            },
            deleteClass(row) {
                this.$confirm(`删除后无法恢复，确认要删除吗？`, "温馨提示", this.$util.confirmBtnText).then(() => {
                    this.$axios.post("/adminapi/v1/tools/classes/delete?classId=" + row.classId).then(response => {
                        if (response.data.error == 10000) {
                            this.getList(this.currentPage);
                            this.$util.successMsg("删除成功");
                        } else {
                            this.$util.errorMsg(response.data.message);
                        }
                    })
                }).catch(() => { })
            },
            handleCurrentChange(val) {
                this.currentPage = val;
                this.getList(val);
            },
            toDet(row) {
                this.saveSelectHistory();
                this.$router.push('/classDet?id=' + row.classId);
            },
            newClass(row) {
                this.saveSelectHistory();
                if (!row) return this.$router.push('/newClass');
                this.$router.push('/newClass?id=' + row.classId);
            },
            saveSelectHistory() {
                let params = {
                    grade: this.gradeId * 1,
                    pageSize: 10,
                    schoolType: this.schoolType,
                    pageNum: this.currentPage * 1,
                    schoolName: this.schoolName
                }
                if (this.gradeId == 0) delete params.grade;
                if (this.schoolId) params.schoolId = this.schoolId;
                this.$util.setStore("classInfo", JSON.stringify(params));
            }

        }
    }
</script>